<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
<!--          <el-form-item label="管理员ID" prop="managerId">-->
<!--            <el-input v-model="queryParams.managerId" placeholder="请输入管理员ID" clearable style="width: 240px" @keyup.enter="handleQuery" />-->
<!--          </el-form-item>-->
          <el-form-item label="设备场地" prop="positionId">
            <el-select v-model="queryParams.positionId" placeholder="请选择" @keyup.enter="handleQuery" clearable="true">
              <el-option
                v-for="item in positionList"
                :key="item.positionId"
                :label="item.name"
                :value="item.positionId"
                :disabled="item.status == 'discard'"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:managerFees:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:managerFees:edit']">修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:managerFees:remove']">删除</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:managerFees:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="managerFeesList" border="true">
        <el-table-column label="#" type="index" width="55" align="center" fixed="left"/>
        <el-table-column label="" align="center" prop="managerFeesId" v-if="false" />
        <el-table-column label="用户" align="center" prop="sysUserName" />
        <el-table-column label="场地ID" align="center" prop="positionId" v-if="false"/>
        <el-table-column label="场地名称" align="center" prop="positionName"/>
        <el-table-column label="总分成金额" align="center" prop="amount" />
        <el-table-column label="冻结金额" align="center" prop="freezeAmount" />
        <el-table-column label="可提现金额" align="center" prop="residueAmount" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="提现" placement="top">
              <el-button link type="primary" icon="Edit" @click="withdraw(scope.row)">提现</el-button>
            </el-tooltip>
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:managerFees:edit']"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:managerFees:remove']"></el-button>-->
<!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改代理商费用记录(场地)对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="managerFeesFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="场地ID" prop="positionId">
          <el-input v-model="form.positionId" placeholder="请输入场地ID" />
        </el-form-item>
        <el-form-item label="分润类型： rate 比例, fix 固定" prop="shareType">
          <el-select v-model="form.shareType" placeholder="请选择分润类型： rate 比例, fix 固定">
            <el-option
                v-for="dict in share_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分润比例" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入分润比例" />
        </el-form-item>
        <el-form-item label="固定费用" prop="fees">
          <el-input v-model="form.fees" placeholder="请输入固定费用" />
        </el-form-item>
        <el-form-item label="总分成金额(来源订单累计)" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入总分成金额(来源订单累计)" />
        </el-form-item>
        <el-form-item label="冻结金额" prop="freezeAmount">
          <el-input v-model="form.freezeAmount" placeholder="请输入冻结金额" />
        </el-form-item>
        <el-form-item label="剩余可提现余额" prop="residueAmount">
          <el-input v-model="form.residueAmount" placeholder="请输入剩余可提现余额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 提现 -->
    <el-dialog v-model="withdrawVisible" title="提现" width="800px">
      <el-form :model="withdrawForm" prop="withdrawAmount">
        <el-form-item label="可提现金额：">
          <el-input-number v-model="withdrawForm.canWithdrawAmount" disabled/>
        </el-form-item>
        <el-form-item label="提 现 金 额：">
          <el-input-number v-model="withdrawForm.withdrawAmount" @change="checkWithdrawAmount" :precision="2" :min="0" :max="withdrawForm.canWithdrawAmount"/>
        </el-form-item>
        <el-form-item label="提 现 备 注：">
          <el-input v-model="withdrawForm.withdrawRemark" maxlength="20" show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="withdrawVisible = false">取消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitWithdraw">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ManagerFees" lang="ts">
import { listManagerFees, getManagerFees, delManagerFees, addManagerFees, updateManagerFees } from '@/api/device/managerFees';
import { ManagerFeesVO, ManagerFeesQuery, ManagerFeesForm } from '@/api/device/managerFees/types';
import {allPosition} from "@/api/device/position";
import {addManagerWithdraw} from "@/api/device/managerWithdraw";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { share_type } = toRefs<any>(proxy?.useDict('share_type'));

const managerFeesList = ref<ManagerFeesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const withdrawVisible = ref(false);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const managerFeesFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ManagerFeesForm = {
  managerFeesId: undefined,
  positionId: undefined,
  shareType: undefined,
  rate: undefined,
  fees: undefined,
  amount: undefined,
  freezeAmount: undefined,
  residueAmount: undefined,
  remark: undefined
}
const data = reactive<PageData<ManagerFeesForm, ManagerFeesQuery>>({
  form: {...initFormData},
  withdrawForm: {
    withdrawAmount: undefined,
    canWithdrawAmount: undefined,
    sysUserId: undefined,
    positionId: undefined,
    withdrawRemark: undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'create_time',
    isAsc: 'desc',
    managerId: undefined,
    positionId: undefined,
    shareType: undefined,
    rate: undefined,
    fees: undefined,
    amount: undefined,
    freezeAmount: undefined,
    residueAmount: undefined,
    params: {
    }
  },
  positionList:[],
  rules: {
    managerFeesId: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    positionId: [
      { required: true, message: "场地ID不能为空", trigger: "blur" }
    ],
    shareType: [
      { required: true, message: "分润类型： rate 比例, fix 固定不能为空", trigger: "change" }
    ],
    rate: [
      { required: true, message: "分润比例不能为空", trigger: "blur" }
    ],
    fees: [
      { required: true, message: "固定费用不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "总分成金额(来源订单累计)不能为空", trigger: "blur" }
    ],
    freezeAmount: [
      { required: true, message: "冻结金额不能为空", trigger: "blur" }
    ],
    residueAmount: [
      { required: true, message: "剩余可提现余额不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules,positionList,withdrawForm } = toRefs(data);

function checkWithdrawAmount() {
  if (withdrawForm.value.withdrawAmount > withdrawForm.value.canWithdrawAmount) {
    withdrawForm.value.withdrawAmount = withdrawForm.value.canWithdrawAmount;
  }
}


const submitWithdraw = async() => {
  console.log(withdrawForm.value.withdrawAmount> 0);
  if(!withdrawForm.value.withdrawAmount && !withdrawForm.value.withdrawAmount > 0){
    proxy?.$modal.msgError("请填写提现金额且需要大于0!");
    return;
  }
  buttonLoading.value = true;
  await addManagerWithdraw(withdrawForm.value).finally(() =>  buttonLoading.value = false);
  proxy?.$modal.msgSuccess("提交成功");
  withdrawVisible.value = false;
  getList();
}

/**
 * 提现
 */
const withdraw = async (row?: ManagerFeesVO) => {
  withdrawForm.value.withdrawAmount = undefined;
  withdrawForm.value.sysUserId = row.sysUserId;
  withdrawForm.value.positionId = row.positionId;
  withdrawForm.value.withdrawRemark = undefined;
  withdrawForm.value.canWithdrawAmount = row.residueAmount;
  withdrawVisible.value = true;
}
const getPositionList = async () => {
  loading.value = true;
  const res = await allPosition();
  positionList.value = res.data;
  loading.value = false;
}


/** 查询代理商费用记录(场地)列表 */
const getList = async () => {
  loading.value = true;
  const res = await listManagerFees(queryParams.value);
  managerFeesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  managerFeesFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ManagerFeesVO[]) => {
  ids.value = selection.map(item => item.managerFeesId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加代理商费用记录(场地)";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ManagerFeesVO) => {
  reset();
  const _managerFeesId = row?.managerFeesId || ids.value[0]
  const res = await getManagerFees(_managerFeesId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改代理商费用记录(场地)";
}

/** 提交按钮 */
const submitForm = () => {
  managerFeesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.managerFeesId) {
        await updateManagerFees(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addManagerFees(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ManagerFeesVO) => {
  const _managerFeesIds = row?.managerFeesId || ids.value;
  await proxy?.$modal.confirm('是否确认删除代理商费用记录(场地)编号为"' + _managerFeesIds + '"的数据项？').finally(() => loading.value = false);
  await delManagerFees(_managerFeesIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('device/managerFees/export', {
    ...queryParams.value
  }, `managerFees_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getPositionList();
});
</script>
